import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import path from 'path'
import { UserConfig, ProxyOptions } from 'vite';

// https://vitejs.dev/config/
interface ProxyConfig {
  [key: string]: ProxyOptions;
}

export default defineConfig(({ mode }): UserConfig => {
  const env = loadEnv(mode, process.cwd(), '');
  // 是否启用代理
  const enableProxy = env.VITE_API_ENABLE_PROXY || false;
  console.log('===========================================');
  console.log('Vite 环境信息');
  console.log('-------------------------------------------');
  console.log('env:', mode);
  console.log('代理是否启用:', enableProxy);
  console.log('代理URL:', env.VITE_API_PROXY_URL);
  console.log('===========================================');

  const proxyConfig: ProxyConfig = enableProxy ? {
    '/api': {
      target: env.VITE_API_PROXY_URL || '',
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/api/, ''),
    }
  } : {};

  return {
    resolve: {
      alias: [
        {
          find: '@',
          replacement: path.resolve(__dirname, './src')
        },
        {
          find: '@components',
          replacement: path.resolve(__dirname, './src/components')
        }
      ],
    },
    css: {
      preprocessorOptions: {
        scss: {
          // 配置 nutui 全局 scss 变量
          additionalData: ``,
        },
      },
    },
    plugins: [
      react()
    ],

    server: {
      proxy: proxyConfig
    },
    define: {
      'import.meta.env.VITE_API_ENABLE_PROXY': JSON.stringify(env.VITE_API_ENABLE_PROXY),
      'import.meta.env.VITE_API_PROXY_URL': JSON.stringify(env.VITE_API_PROXY_URL),
      'import.meta.env.MODE': JSON.stringify(mode),
    },
    build: {
      // 添加源映射以便调试
      sourcemap: true,
    }
  };
});
